<?php
/**
 * Created by PhpStorm.
 * User: shaowei
 * Date: 2019/5/18
 * Time: 下午6:09
 */

namespace App\Http\Model;

use Illuminate\Support\Facades\DB;

class GiftPearlBag extends Base
{
    protected $table = 'gift_pearl_bag';
    protected $primaryKey = 'id';
    protected $giftPearlBagLogTable = 'gift_pearl_bag_log';
    protected $giftPearlLibraryTable = 'gift_pearl_library';

    public function __construct(array $attributes = [])
    {
        parent::__construct($this->table, $attributes);
    }

    /**
     * 变更背包礼物
     * @param $userId  用户ID
     * @param $toUserId  获取礼物用户ID，获得礼物设置为0
     * @param $giftId 礼物ID
     * @param $change 变更礼物的数量 送礼物时为负数
     * @param int $platformType 来源类型（0=默认） 6.新用户赠送
     */
    public function inc($userId, $toUserId, $giftId, $change, $platformType = 0)
    {
        // 此处执行标识
        $flag = true;

        // 更新背包剩余数
        $increment = DB::table($this->table)
            ->where('user_id', '=', $userId)
            ->where('gift_id', '=', $giftId)
            ->increment('avail', $change, ['update_timestamp' => time()]);

        if (!$increment) {
            // 创建背包默认数据
            $insertBag = DB::table($this->table)->insert([
                'user_id' => $userId,
                'gift_id' => $giftId,
                'avail' => $change,
                'create_timestamp' => time(),
                'update_timestamp' => time()
            ]);
            if (!$insertBag) {
                $flag = false;
            }
        }

        if ($flag) {
            // 创建背包日志
            $insertBagLog = DB::table($this->giftPearlBagLogTable)->insert([
                'user_id' => $userId,
                'gift_id' => $giftId,
                'to_user_id' => $toUserId,
                'change' => $change,
                'avail' => 0,
                'platform_type' => $platformType,
                'create_timestamp' => time()
            ]);
            if (!$insertBagLog) {
                $flag = false;
            }
        }

        return $flag;
    }

    /**
     * 礼物背包列表
     * */
    public function giftBagList($condition = [], $page = 0, $limit = 10)
    {
        // 总条数
        $totalCount = DB::table($this->table)
            ->where($condition)
            ->count('gift_id');

        $result = DB::table($this->table)
            ->where($condition)
            ->leftJoin($this->giftPearlLibraryTable, $this->table . '.gift_id', '=', $this->giftPearlLibraryTable . '.gift_id')
            ->orderBy($this->giftPearlLibraryTable . '.price', 'asc')
            ->offset($page * $limit)
            ->limit($limit)
            ->get([
                $this->table . '.gift_id',
                $this->table . '.user_id',
                $this->table . '.avail',
                $this->giftPearlLibraryTable . '.name',
                $this->giftPearlLibraryTable . '.image',
                $this->giftPearlLibraryTable . '.price',
                $this->giftPearlLibraryTable . '.animate_resource',// 动画资源包链接
            ]);

        $result = self::objToArray($result);

        // 增加图片URL domain
        foreach ($result as $key => $value) {
            if (!empty($value['animate_resource'])) {
                $result[$key]['animate_resource'] = getPicDomain() . $result[$key]['animate_resource'];
            }
            $result[$key]['image'] = getPicDomain() . $result[$key]['image'];
        }

        return $this->checkPageData($page, $limit, $totalCount, $result);
    }

    /**
     * 查询
     * */
    public function get($params = [], $isSingle = false)
    {
        if ($isSingle) {
            $result = DB::table($this->table)->where($params)->first();
            return self::objToArray($result);
        } else {
            $result = DB::table($this->table)->where($params)->orderBy('id', 'desc')->get()->toArray();
            return self::objToArray($result);
        }
    }


    public function getAll($userId){
        $result = DB::table($this->table)
            ->where([['user_id', '=', $userId], ['avail', '>', 0]])
            ->leftJoin($this->giftPearlLibraryTable, $this->table . '.gift_id', '=', $this->giftPearlLibraryTable . '.gift_id')
            ->orderBy($this->giftPearlLibraryTable . '.price', 'asc')
            ->get([
                $this->table . '.gift_id',
                $this->table . '.user_id',
                $this->table . '.avail',
                $this->giftPearlLibraryTable . '.name',
                $this->giftPearlLibraryTable . '.image',
                $this->giftPearlLibraryTable . '.price',
                $this->giftPearlLibraryTable . '.animate_resource',// 动画资源包链接
                $this->giftPearlLibraryTable . '.gift_label_id',
            ]);

        $result = self::objToArray($result);

        // 增加图片URL domain
        foreach ($result as $key => $value) {
            if (!empty($value['animate_resource'])) {
                $result[$key]['animate_resource'] = getPicDomain() . $result[$key]['animate_resource'];
            }
            $result[$key]['image'] = getPicDomain() . $result[$key]['image'];
        }
        return $result;
    }



}